<?php
namespace Admin\Controller;

use Common\Controller\AdminbaseController;
use Common\Model\UserAmountModel;

class GuestController extends AdminbaseController{

    /**
     * 竞猜管理页面
     */
    public function index(){
        $live_id = I("live_id");
        if(!$live_id){
            return $this->error("直播id为空");
        }
        $live = M("vrlive.live",null);
        $live_info = $live->where(array('live_id'=>$live_id))->field('start_time,status')->find();
        if(!$live_info){
            return $this->error("直播不存在");
        }
        $start_time = strtotime($live_info['start_time']);
        if($start_time > time()){  //开始时间大于当前时间：未开始
            $status = 3;
        }else if($start_time <= time()){ //开始时间小于当前时间：直播中
            $status = 4;
        }else{
            $status = $live_info['status'];
        }
        $quiz = M("vrnews1.news_quiz", null);
        $count = $quiz->where(array('news_id'=>$live_id))->count();
        if($count >= 1){
            $quiz_list = $quiz->join('vrnews1.quiz z on z.quiz_id = news_quiz.quiz_id and news_quiz.news_id = "'.$live_id.'"')
                ->join('vruser1.user_quiz q on z.quiz_id = q.quiz_id ','left')
                ->join('vrnews1.quiz_rule r on r.rule_id = z.correct_id','left')
                ->group("z.quiz_id")->field('z.*,r.rule_name,sum(q.amount) as total_amount,count(q.user_id) as num')->select();
            foreach ($quiz_list as $key=>$val){
                $user_quiz = M("vruser1.user_quiz",null);
                $quiz_list[$key]['is_quiz'] = $user_quiz->where(array('quiz_id'=>$val['quiz_id'],'news_id'=>$live_id))->count();
            }
        }else{
            $quiz_list = array();
        }
        $this->assign('live_id', $live_id);
        $this->assign('list', $quiz_list);
        $this->assign('status', $status);
        $this->display();
    }

    /**
     * 添加竞猜题目
     */
    public function add(){
        $id = I("id");
        $live_id = I("live_id");
        $quiz    = M("vrnews1.quiz",null);
        $rule    = M("vrnews1.quiz_rule",null);
        $quiz_info = $quiz->where(array('quiz_id'=>$id))->find();
        $answer    = $rule->where(array('quiz_id'=>$id))->select();
        $this->assign('id', $id);
        $this->assign('live_id', $live_id);
        $this->assign('quiz_info', $quiz_info);
        $this->assign('answer', $answer);
        $this->display();
    }

    /**
     * 添加或修改题目
     */
    public function add_answer(){
        $id = I("id");
        $live_id = I("live_id");
        $task_name = I("task_name");
        $answer    = I("answer");
        if(empty($answer)){
            return $this->error("题目答案不能为空");
        }
        $quiz = M("vrnews1.quiz",null);
        $quiz_data['quiz_name'] = $task_name;
        if(!empty($id)){
            $quiz->where(array('quiz_id'=>$id))->save($quiz_data);
            $quiz_data['quiz_id'] = $id;
        }else{
            $quiz_data['quiz_id']    = time().$this->getRange();
            $quiz_data['created_at'] = date('Y-m-d H:i:s', time());
            $quiz->add($quiz_data);
            $news_quiz = M("vrnews1.news_quiz",null);
            $news_data['id']      = time().$this->getRange();
            $news_data['news_id'] = $live_id;
            $news_data['quiz_id'] = $quiz_data['quiz_id'];
            $news_quiz->add($news_data);
        }
        
        /* for ($i=1;$i<count($answer);$i++){
            $dataList[] = array('rule_id'=>time().$this->getRange(),'quiz_id'=>$quiz_data['quiz_id'],'rule_name'=>$answer[$i], 'sort_num'=>);
        } */
        $dataList = array();
        foreach($answer as $key=>$val){
        	$dataList[] = array('rule_id'=>time().$this->getRange(),'quiz_id'=>$quiz_data['quiz_id'],'rule_name'=>$val, 'sort_num'=>$key);
        }
        
        if($dataList){
            $rule = M("vrnews1.quiz_rule",null);
            $rule->where(array('quiz_id'=>$quiz_data['quiz_id']))->delete();
            $rule->addAll($dataList);
        }

        $this->success('发布成功！', U("Admin/Guest/index",array('live_id'=>$live_id)));
    }

    /**
     * 设置公布结果弹窗
     */
    public function setFull(){
        $quiz_id = I("id");
        $live_id = I("live_id");
        $quiz    = M("vrnews1.quiz",null);
        $rule    = M("vrnews1.quiz_rule",null);
        $quiz_info = $quiz->where(array('quiz_id'=>$quiz_id))->find();
        $answer    = $rule->where(array('quiz_id'=>$quiz_id))->order(array('sort_num'=>'ASC'))->select();
        $this->assign("quiz_id", $quiz_id);
        $this->assign("live_id", $live_id);
        $this->assign("quiz_info", $quiz_info);
        $this->assign("answer", $answer);
        $this->display('setfull');
    }

    /**
     * 删除竞猜题目
     */
    public function delete(){
        $quiz_id = I("quiz_id");
        $live_id = I("live_id");
        $quiz    = M("vrnews1.quiz",null);
        $rule    = M("vrnews1.quiz_rule",null);
        $news_quiz = M("vrnews1.quiz_rule",null);
        $quiz_info = $quiz->where(array('quiz_id'=>$quiz_id))->find();
        if(!$quiz_info){
            return $this->error("竞猜题目不存在");
        }
        $quiz_result = $quiz->where(array('quiz_id'=>$quiz_id))->delete();
        $rule_result = $rule->where(array('quiz_id'=>$quiz_id))->delete();
        $news_result = $news_quiz->where(array('quiz_id'=>$quiz_id,'news_id'=>$live_id))->delete();
        if ($quiz_result && $rule_result && $news_result) {
            $this->success("删除成功！");
        } else {
            return $this->error($news_result['Message']);
        }
    }

    /**
     * 公布结果
     */
    public function publish(){
        $answer = I("answer");
        $id     = I("id");
        $live_id = I("live_id");
        $quiz   = M("vrnews1.quiz",null);
        $data['correct_id'] = $answer;
        $quiz->where(array('quiz_id'=>$id))->save($data);
//      用户投注数量+（用户投注数量/此答案总投注数量）X（此竞此题目所有投注数量-此答案总投注数量）
        $user_quiz = M("vruser1.user_quiz",null);
        //此竞猜题目所有投注数量
        $quiz_amount = $user_quiz->where(array('quiz_id'=>$id, 'news_id'=>$live_id))->field("sum(amount) as total_amount")->find();
        //此答案总投注数量
        $rule_amount = $user_quiz->where(array('quiz_id'=>$id, 'news_id'=>$live_id, 'rule_id'=>$answer))->field("sum(amount) as total_amount")->find();
        //获取所有投注该答案的用户
        $user_list = $user_quiz->where(array('quiz_id'=>$id, 'news_id'=>$live_id, 'rule_id'=>$answer))->select();
        if(!empty($user_list)){
            $a = 0;
            foreach ($user_list as $key=>$val){
                //计算用户获胜金额
                $won_cnt = $val['amount']+($val['amount']/$rule_amount['total_amount'])*($quiz_amount['total_amount']-$rule_amount['total_amount']);
                $data['won_cnt'] = $won_cnt;
                //更新用户获胜金额
                $user_quiz->where(array('quiz_id'=>$id, 'news_id'=>$live_id, 'rule_id'=>$answer,'user_id'=>$val['user_id']))->save($data);
                $param['user_id'] = $val['user_id'];
                $param['operate_cnt'] = $won_cnt;
                $param['operate'] = 1;
                $param['operate_name'] = '竞猜';
                $userAmount = new UserAmountModel();
                $userAmount->addUserAmount($param);
                $a++;
            }
        }
        if($a == count($user_list)){
            echo 1;exit();
        }else{
            echo 2;exit();
        }
    }

    /**
     * 详情弹窗
     */
    public function setDetail(){
        $quiz_id = I("id");
        $quiz    = M("vrnews1.quiz",null);
        $rule    = M("vrnews1.quiz_rule",null);
        $quiz_info = $quiz->join('vruser1.user_quiz q on quiz.quiz_id = q.quiz_id ','left')
            ->join('vrnews1.quiz_rule r on r.rule_id = quiz.correct_id','left')
            ->where(array('quiz.quiz_id'=>$quiz_id))
            ->group("q.quiz_id")->field('quiz.*,r.rule_name,sum(q.amount) as total_amount,count(q.user_id) as num')->find();
        $answer_info = $rule->join("vruser1.user_quiz z on z.rule_id = quiz_rule.rule_id","left")
                        ->where(array('quiz_rule.quiz_id'=>$quiz_id))
                        ->field('quiz_rule.*,sum(z.amount) as total_amount,count(z.user_id) as num')
                        ->group("quiz_rule.rule_id")
                        ->select();
        if(!empty($answer_info)){
            $total_num = 0;
            foreach ($answer_info as $key=>$val){
                $total_num += $val['num'];
            }
        }
        $this->assign("total_num", $total_num);
        $this->assign("quiz_id", $quiz_id);
        $this->assign('quiz_info',$quiz_info);
        $this->assign('answer_info', $answer_info);
        $this->display('setdetail');
    }

    /**
     * 参与人数管理
     */
    public function joinManage(){
        $id = I("id");
        $start_time = I("start_time");
        $end_time   = I("end_time");
        $phone      = I("phone");
        $nickname   = I("nickname");
        $amount     = I("amount");
        $won_cnt    = I("won_cnt");
        $where['user_quiz.quiz_id'] = $id;
        if($start_time){
            $where['user_quiz.created_at'] = array('EGT', $start_time);
        }
        if($end_time){
            $where['user_quiz.created_at'] = array('LT', $end_time);
        }
        if($phone){
            $where['u.mobile_phone'] = array('eq', $phone);
        }
        if($nickname){
            $where['u.nickname'] = array('eq', $nickname);
        }
        if($amount){
            $where['user_quiz.amount'] = array('eq', $amount);
        }
        if($won_cnt){
            $where['user_quiz.won_cnt'] = array('eq', $won_cnt);
        }
        $user_quiz  = M("vruser1.user_quiz",null);
        $list = $user_quiz->join("vruser1.user u on u.user_id=user_quiz.user_id","left")
                ->join("vrnews1.quiz q on q.quiz_id=user_quiz.quiz_id","left")
                ->join("vrnews1.quiz_rule r on r.rule_id=user_quiz.rule_id","left")
                ->where($where)
                ->field("user_quiz.created_at,u.mobile_phone,u.nickname,r.rule_name,user_quiz.amount,user_quiz.won_cnt,user_quiz.user_id")
                ->select();
        $this->assign('list', $list);
        $this->assign('id', $id);
        $this->assign('start_time', $start_time);
        $this->assign('end_time', $end_time);
        $this->assign('phone', $phone);
        $this->assign('nickname', $nickname);
        $this->assign('amount', $amount);
        $this->assign('won_cnt', $won_cnt);
        $this->display('joinmanage');
    }
}